<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/14
 * Time: 17:27
 */

namespace app\index\logic;

use think\Loader;
use think\DB;
use think\Exception;

class Sync
{
    public function syncProduct()
    {
        $pro = Loader::model('Product');
        $act = Loader::model('Activity');

        $replace_product = $pro->getReplaceProduct();
        $disable_product = $pro->getDisableProduct();
        $disable_product = array_merge($replace_product, $disable_product);

        $enable_product = $pro->getEnableProduct();

        try {
            DB::startTrans();
            if ($disable_product) {
                $pro->deleteProduct(array_column($disable_product, 'id'));
                $act->deleteActivity(array_column($disable_product, 'activity_id'));
            }

            if ($enable_product) {
                $pro->addProduct(array_column($enable_product, 'id'));
                $act->addActivity(array_column($enable_product, 'activity_id'));
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw new Exception($e->getMessage());
        }
    }

    public function syncOrder()
    {
        $ord = Loader::model('Order');

        $newOrder = $ord->getNewOrder();
        $refundOrder = $ord->getRefundOrder();

        try {
            DB::startTrans();
            if ($newOrder) $ord->addOrder($ord->getOrderArr(array_column($newOrder, 'id')));
            if ($refundOrder) $ord->refundOrder(array_column($refundOrder, 'id'));
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw new Exception($e->getMessage());
        }
    }

    public function syncYouZanOrder($ord_arr)
    {
        $ord = Loader::model('Order');
        try {
            DB::startTrans();
            $ord->addOrder($ord_arr);
            DB::commit();
        } catch (Exception $e) {
            DB::rollback();
            throw new Exception($e->getMessage());
        }
    }
}